package cn.zebra.dev.mall.module.product.controller;

import cn.zebra.dev.common.restful.Result;
import cn.zebra.dev.ibatis.plus.utils.PageUtils;
import cn.zebra.dev.mall.module.product.dto.ProductCommentListDTO;
import cn.zebra.dev.mall.module.product.vo.ProductCommentAppendVO;
import cn.zebra.dev.mall.module.product.vo.ProductCommentVO;
import cn.zebra.dev.member.module.login.service.SecurityMemberService;
import cn.zebra.dev.order.module.item.entity.OrdersItemEntity;
import cn.zebra.dev.order.module.item.service.OrdersItemService;
import cn.zebra.dev.product.module.collect.entity.MemberProductCollectEntity;
import cn.zebra.dev.product.module.comment.entity.ProductCommentAppendEntity;
import cn.zebra.dev.product.module.comment.entity.ProductCommentEntity;
import cn.zebra.dev.product.module.product.entity.ProductEntity;
import cn.zebra.dev.product.module.product.service.ProductService;
import cn.zebra.dev.product.module.sku.entity.ProductSkuEntity;
import cn.zebra.dev.product.module.sku.service.ProductSkuService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import cn.zebra.dev.product.module.comment.service.ProductCommentAppendService;
import cn.zebra.dev.product.module.comment.service.ProductCommentService;

import javax.validation.Valid;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@Api(tags = "商品评价")
@RestController
@RequestMapping("/product/comment")
public class ProductCommentController {

    @Autowired
    private SecurityMemberService securityMemberService;

    @Autowired(required = false)
    private ProductCommentService productCommentService;

    @Autowired(required = false)
    private ProductCommentAppendService productCommentAppendService;

    @Autowired
    private OrdersItemService ordersItemService;

    @Autowired
    private ProductSkuService productSkuService;

    @Autowired
    private ProductService productService;



    @GetMapping("/list/{productId}")
    @ApiOperation("商品评价列表")
    public Result <PageUtils<ProductCommentListDTO>> list(
            @RequestParam(value = "limit", defaultValue = "10", required = false) Integer limit,
            @RequestParam(value = "page", defaultValue = "1", required = false) Integer page,
            @PathVariable Long productId){
        Map<String, Object> map = new HashMap<>();
        map.put("limit", limit);
        map.put("page", page);
        map.put("productId",productId);
        PageUtils<ProductCommentEntity> pageUtils = productCommentService.findPage(map);
        PageUtils<ProductCommentListDTO> data = new PageUtils<>(pageUtils);
        List<ProductCommentEntity> list =pageUtils.getList();
        Integer count = productCommentService.count("product_id = {0}",productId);
        ProductEntity productEntity = productService.findById(productId);
        if(list.size() > 0){
            List<ProductCommentListDTO> dtos = new ArrayList<>();
            List<Long> productCommentIds = list.stream().map(ProductCommentEntity::getId).collect(Collectors.toList());
            List<ProductCommentAppendEntity> appendEntities = productCommentAppendService.findByIds(productCommentIds);
            list.forEach(entity ->{
                Long appendCommentID = entity.getId();
                Optional<ProductCommentAppendEntity> optional = appendEntities.stream().filter(productCommentAppendEntity  -> productCommentAppendEntity.getProductCommentId().equals(appendCommentID)).findAny();
                if(optional.isPresent()){
                    ProductCommentAppendEntity commentAppendEntity = optional.get();
                    ProductCommentListDTO dto = new ProductCommentListDTO();
                    BeanUtils.copyProperties(entity,dto);
                    dto.setAppendImageUrl(commentAppendEntity.getAppendImageUrl());
                    dto.setAppendContent(commentAppendEntity.getAppendContent());
                    dto.setCount(count);
                    dto.setSellNum(productEntity.getSellNum());
                    dtos.add(dto);
                }
            });
                data.setList(dtos);
        }
        return Result.success(data);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("查看评论详情")
    public Result<ProductCommentListDTO> get(@PathVariable Long id) {
        ProductCommentEntity commentEntity = productCommentService.findById(id);
        ProductCommentAppendEntity appendEntity = productCommentAppendService.selectOne("product_comment_id = {0}",id);
        ProductCommentListDTO dto = new ProductCommentListDTO();
        BeanUtils.copyProperties(commentEntity, dto);
        if(commentEntity == null){
            return Result.error("没有该评论!");
        }
        if(appendEntity == null){
            dto.setAppendContent("");
            dto.setAppendImageUrl("");
        }else{
            dto.setAppendContent(appendEntity.getAppendContent());
            dto.setAppendImageUrl(appendEntity.getAppendImageUrl());
        }
        return Result.success(dto);
    }


    @PostMapping("/save")
    @ApiOperation("保存商品评价")
    public Result save(@Valid @RequestBody ProductCommentVO vo){
        OrdersItemEntity orderItem = ordersItemService.selectOne(vo.getOrdersId());
        if(orderItem == null){
            return Result.error("订单不存在,不能评价");
        }
        ProductCommentEntity commentEntity = new ProductCommentEntity();
        BeanUtils.copyProperties(vo,commentEntity);
        Long memberId = securityMemberService.getMemberId();
        String memberHeadImg = securityMemberService.getMemberPhoto();
        String memberName = securityMemberService.getMemberName();
        ProductCommentEntity commentEntity1 = productCommentService.selectOne("member_id = {0}",memberId);
       //根据用户id查评论表  没有才可以评论  一个用户只能评论一次
        if(commentEntity1 != null){
            return Result.error("您已评论过，无需再评论");
        }
        commentEntity.setProductAttributes(orderItem.getProductAttributes());
        commentEntity.setImageUrl(vo.getImageUrl());
        commentEntity.setMemberId(memberId);
        commentEntity.setMemberName(memberName);
        commentEntity.setMemberHeadImg(memberHeadImg);
        ProductEntity entity = productService.findById(orderItem.getProductId());
        commentEntity.setProductId(entity.getId());
        ProductSkuEntity skuEntity = productSkuService.findById(entity.getId());
        commentEntity.setProductSkuId(skuEntity.getId());
        commentEntity.setCreateTime(LocalDateTime.now());
        if(productCommentService.save(commentEntity)){
            return Result.success("保存成功!");
        }
       return Result.error("保存失败!");
    }


    @PostMapping("/append")
    @ApiOperation("商品追加评价")
    public Result append(@Valid @RequestBody ProductCommentAppendVO vo){
        ProductCommentAppendEntity entity = new ProductCommentAppendEntity();
        BeanUtils.copyProperties(vo,entity);
        ProductCommentEntity commentEntity = productCommentService.findById(vo.getProductCommentId());
        ProductCommentAppendEntity appendEntity = productCommentAppendService.selectOne("product_comment_id = {0}",vo.getProductCommentId());
        //根据商品追加表的商品评论id查评论表  没有就先评论才能追加评论
        if(commentEntity == null){
            return Result.error("还未评论商品，请先评论!");
        }
        //根据商品评论id查追加评论表  没有才能追评
        if(appendEntity != null){
            return Result.error("您已追评过，无需再追评");
        }
            entity.setMemberId(commentEntity.getMemberId());
            entity.setProductCommentId(vo.getProductCommentId());
            entity.setCreateDate(LocalDateTime.now());
            entity.setProductCommentId(vo.getProductCommentId());
            entity.setAppendImageUrl(vo.getImageUrl());
                if(productCommentAppendService.save(entity)){
                    return Result.success("追评成功!");
                }
        return Result.error("追评失败!");
    }
}
